<?php

require(ROOT . '/controllers/CommonController.class.php');

class PermissionController extends CommonController {

	public function __construct() {
		parent::__construct(__CLASS__);

		$this->db = DB::open('reading');

		$this->model = new Model('permission', $this->db);
	}

	public function indexAction() {
		$records = $this->model->query();

		$this->assign('records', $records);

		$this->rend('index');
	}

	public function newAction() {
		$userModel = new Model('user', $this->db);

		$this->assign('users', $userModel->query());
		
		$this->rend('new');
	}

	public function insertAction() {
		$data = array(
			'user_id' => requestPost('user_id'),
			'permission' => str_replace(array(" ", "\t", "\n"), '', requestPost('permission')),
			'created_at' => time()
		);

		if ($this->model->insert($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('permission/index'));
	}

	public function editAction($segments) {
		$id = (int) $segments[0];

		$record = $this->model->find($id);

		$userModel = new Model('user', $this->db);

		$this->assign('users', $userModel->query());

		$this->assign('record', $record);

		$this->rend('edit');
	}

	public function updateAction() {
		$data = array(
			'id' => requestPost('id'),
			'user_id' => requestPost('user_id'),
			'permission' => str_replace(array(" ", "\t", "\n"), '', requestPost('permission')),
		);

		if ($this->model->update($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('permission/index'));
	}

	public function deleteAction($segments) {
		$id = (int) $segments[0];

		if ($this->model->delete($id)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('permission/index'));
	}

}
